package servers

import (
	"context"
	"time"

	"gitee.com/bitwormhole/mails-pnp-driver/lib/common/vo"
	"gitee.com/bitwormhole/mails-pnp-driver/lib/pnp"
	"github.com/starter-go/application"
)

// PNPServiceImpl ...
type PNPServiceImpl struct {

	//starter:component

	_as func(pnp.Service) //starter:as("#")

	channel chan vo.MessageJSON
}

func (inst *PNPServiceImpl) _impl() pnp.Service {
	return inst
}

// Life ...
func (inst *PNPServiceImpl) Life() *application.Life {
	return &application.Life{
		OnCreate:  inst.open,
		OnDestroy: inst.close,
	}
}

func (inst *PNPServiceImpl) open() error {
	ch := make(chan vo.MessageJSON, 16)
	inst.channel = ch
	return nil
}

func (inst *PNPServiceImpl) close() error {
	ch := inst.channel
	inst.channel = nil
	if ch != nil {
		close(ch)
	}
	return nil
}

// Push ...
func (inst *PNPServiceImpl) Push(c context.Context, msg *vo.Message) error {
	j := msg.ToJSON()
	inst.channel <- j
	return nil
}

// Pull ...
func (inst *PNPServiceImpl) Pull(c context.Context, timeout time.Duration) (*vo.Message, error) {
	j := <-inst.channel
	return j.ToMessage()
}
